﻿using System.Text.Json;
using System.Text.Json.Serialization;

namespace Simple.Common.Json.SystemTextJson;

/// <summary>
/// DateTime 格式转换
/// </summary>
public class DateTimeJsonConverter : JsonConverter<DateTime?>
{
    public string Format { get; }

    public DateTimeJsonConverter(string format = "yyyy-MM-ddTHH:mm:ss")
    {
        Format = format;
    }

    public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.Null)
        {
            return null;
        }
        else
        {
            if (reader.TryGetDateTime(out DateTime dateTime))
            {
                return dateTime;
            }
            else
            {
                // Handle conversion failure here, such as throwing an exception or returning a default value
                return null;
            }
        }
    }

    public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
    {
        if (value.HasValue)
        {
            writer.WriteStringValue(value.Value.ToString(Format));
        }
        else
        {
            writer.WriteNullValue();
        }
    }
}


/// <summary>
/// Enum 转换
/// </summary>
public class EnumJsonConverter : JsonConverter<Enum>
{
    public override bool CanConvert(Type typeToConvert)
    {
        return typeToConvert.IsEnum;
    }

    public override Enum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        string? value = reader.TokenType switch
        {
            JsonTokenType.Number => reader.GetInt32().ToString(),
            JsonTokenType.String => reader.GetString(),
            _ => "0",
        };

        if (value == null)
        {
            throw new ArgumentNullException(nameof(value));
        }

        if (Enum.TryParse(typeToConvert, value, out var result))
        {
            return result as Enum;
        }
        throw new InvalidOperationException("值不在枚举范围中");
    }

    public override void Write(Utf8JsonWriter writer, Enum value, JsonSerializerOptions options)
    {
        // 数字
        writer.WriteNumberValue(Convert.ToInt32(value));
    }
}
